package com.geek;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");

        //输出到页面
        PrintWriter out = resp.getWriter();

        //从客户端获取cookie
        Cookie[] cookies = req.getCookies();

        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals("lastime")) {
                    String value = cookie.getValue();
                    System.out.println(value);
                    long aLong = Long.parseLong(value);
                    Date date = new Date(aLong);
                    out.write("上次访问的时间：" + date.toLocaleString());
                }
            }
        } else {
            out.write("Your first visit！");
        }
        Cookie cookie = new Cookie("lastime", System.currentTimeMillis() + "");
//        cookie.setMaxAge(0);
        resp.addCookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
